<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="90px"
    >
      <!-- <el-form-item label="轮播标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入轮播标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="轮播图位置" prop="location">
        <el-select
          v-model="queryParams.location"
          placeholder="请选择轮播图位置"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in locationOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="链接类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择链接类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mall:swiper:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mall:swiper:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mall:swiper:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mall:swiper:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="swiperList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="轮播ID" align="center" prop="id" /> -->
      <el-table-column label="轮播图" align="center" prop="img">
        <template slot-scope="scope">
          <my-image
            style="width:80px;height:50px;"
            :src="scope.row.img"
            preview
          />
        </template>
      </el-table-column>
      <el-table-column
        label="轮播图位置"
        align="center"
        prop="location"
        :formatter="locationFormat"
      />
      <el-table-column label="轮播标题" align="center" prop="title" />

      <el-table-column
        label="链接类型"
        align="center"
        prop="type"
        :formatter="typeFormat"
      />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['mall:swiper:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['mall:swiper:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播标题" />
        </el-form-item>
        <el-form-item label="轮播图(视频封面)" prop="img">
          <imageUpload v-model="form.img" />
        </el-form-item>
        <el-form-item label="轮播图位置" prop="location">
          <el-select v-model="form.location" placeholder="请选择轮播图位置">
            <el-option
              v-for="dict in locationOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="链接类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择链接类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.type == 1 || form.type == 2"
          label="链接目标"
          prop="targetId"
        >
          <div v-if="form.type == 1">
            <el-autocomplete
              v-model="form.targetName"
              :fetch-suggestions="querySearchAsync"
              placeholder="文章标题"
              value-key="title"
              @select="handleSelect"
            />
          </div>
          <div v-if="form.type == 2">
            <imageUpload v-model="form.targetId" type="2" accept="video/*" />
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSwiper,
  getSwiper,
  delSwiper,
  addSwiper,
  updateSwiper,
  exportSwiper
} from '@/api/mall/swiper'
import { listArticle, getArticle } from '@/api/mall/article'
import ImageUpload from '@/components/ImageUpload'

export default {
  name: 'Swiper',
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 轮播管理表格数据
      swiperList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 链接类型字典
      typeOptions: [],
      // 轮播图位置字典
      locationOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        img: null,
        type: null,
        targetId: null,
        location: null,
        sort: null
      },
      // 表单参数
      form: {
        type: 0
      },
      videoSrc:
        '/profile/upload/2021/10/25/550e1e1a-a48b-4cae-9ba7-74fdca3c3834.mp4',
      // 表单校验
      rules: {
        img: [{ required: true, message: '轮播图不能为空', trigger: 'blur' }],
        location: [
          { required: true, message: '轮播图位置不能为空', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择链接类型', trigger: 'change' }
        ],
        targetId: [
          {
            validator: (rule, value, callback) => {
              if (this.form.type != 0 && !value) {
                callback(new Error('链接目标不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('mall_swiper_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('mall_swiper_location').then(response => {
      this.locationOptions = response.data
    })
  },
  methods: {
    querySearchAsync(queryString, cb) {
      listArticle({ title: queryString }).then(res => {
        console.log(res.rows)
        if (res.rows.length > 0) {
          cb(res.rows)
        } else {
          this.form.targetName = ''
          cb([])
          this.$message('查无文章')
        }
      })
    },
    handleSelect(item) {
      console.log(item)
      this.form.targetId = item.id
    },
    /** 查询轮播管理列表 */
    getList() {
      this.loading = true
      listSwiper(this.queryParams).then(response => {
        this.swiperList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 链接类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 轮播图位置字典翻译
    locationFormat(row, column) {
      return this.selectDictLabel(this.locationOptions, row.location)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        img: null,
        type: null,
        targetId: null,
        delFlag: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        location: null,
        sort: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加轮播管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSwiper(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改轮播管理'
        console.log(row.targetId)
        if (row.type == 1) {
          getArticle(row.targetId).then(r => {
            this.$set(this.form, 'targetName', r.data.title)
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSwiper(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSwiper(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(
        '是否确认删除轮播管理编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delSwiper(ids)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有轮播管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return exportSwiper(queryParams)
        })
        .then(response => {
          this.download(response.msg)
        })
    }
  }
}
</script>
